<template>
  <div class="dispatch-list-container">
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="报案号">
            <el-input v-model="searchForm.reportId" placeholder="请输入报案号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="查勘员">
            <el-input v-model="searchForm.surveyorWorkNo" placeholder="请输入查勘员工号" clearable
                      style="width: 200px" />
          </el-form-item>
          <el-form-item label="调度状态">
            <el-select v-model="searchForm.dispatchStatus" placeholder="请选择调度状态" clearable
                       style="width: 200px">
              <el-option label="待确认" :value="1" />
              <el-option label="已确认" :value="2" />
              <el-option label="查勘中" :value="3" />
              <el-option label="查勘完成" :value="4" />
              <el-option label="已取消" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset" :icon="Refresh">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <div class="action-buttons">
        <el-button @click="handleExport" :icon="Download">
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card>
        <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" stripe border
                  style="width: 100%">
          <!-- <el-table-column prop="dispatchId" label="调度ID" width="100" /> -->
          <el-table-column prop="reportId" label="报案号" width="200" />
          <el-table-column prop="policyId" label="保单编号" width="200" />
          <el-table-column prop="surveyorName" label="查勘员" width="120" />
          <el-table-column prop="surveyAddress" label="查勘地点" width="200" show-overflow-tooltip />
          <el-table-column prop="scheduledStartTime" label="计划查勘时间" width="250">
            <template #default="{ row }">
              {{ formatDateTime(row.scheduledStartTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="dispatchStatus" label="调度状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.dispatchStatus)">
                {{ getStatusText(scope.row.dispatchStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="dispatchTime" label="调度时间" width="250">
            <template #default="{ row }">
              {{ formatDateTime(row.dispatchTime) }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="surveyorConfirmTime" label="确认时间" width="160">
              <template #default="{ row }">
                  {{ formatDateTime(row.surveyorConfirmTime) }}
              </template>
          </el-table-column> -->
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <!-- <el-button type="primary" size="small" @click="handleEdit(scope.row)" :icon="Edit">
                编辑
              </el-button> -->
              <el-button type="success" size="small" @click="handleView(scope.row)" :icon="View">
                查看
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)" :icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                         :page-sizes="[5, 10, 20, 50, 100]" :total="pagination.total"
                         layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :before-close="handleDialogClose">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px"><br>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报案号">
              <el-input v-model="formData.reportId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="查勘员工号">
              <el-input v-model="formData.surveyorName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="查勘地点">
              <el-input v-model="formData.surveyAddress" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划开始时间">
              <el-date-picker v-model="formData.scheduledStartTime" type="datetime" disabled
                              style="width: 100%" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度状态" prop="dispatchStatus">
              <el-select v-model="formData.dispatchStatus" placeholder="请选择调度状态" style="width: 100%">
                <el-option label="待确认" :value="1" />
                <el-option label="已确认" :value="2" />
                <el-option label="查勘中" :value="3" />
                <el-option label="查勘完成" :value="4" />
                <el-option label="已取消" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="调度备注">
              <el-input v-model="formData.dispatchRemark" type="textarea" :rows="3" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="formData.dispatchStatus === 5">
          <el-col :span="24">
            <el-form-item label="取消原因" prop="cancelReason">
              <el-input v-model="formData.cancelReason" type="textarea" :rows="2" placeholder="请输入取消原因" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleDialogClose">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="调度详情" width="800px">
      <el-descriptions :column="2" border>
        <!-- <el-descriptions-item label="调度ID">{{ viewData.dispatchId }}</el-descriptions-item> -->
        <el-descriptions-item label="报案号">{{ viewData.reportId }}</el-descriptions-item>
        <el-descriptions-item label="保单编号">{{ viewData.policyId }}</el-descriptions-item>
        <el-descriptions-item label="查勘员">{{ viewData.surveyorName }}</el-descriptions-item>
        <el-descriptions-item label="查勘地点" :span="2">{{ viewData.surveyAddress }}</el-descriptions-item>

        <el-descriptions-item label="计划开始时间">{{ formatDateTime(viewData.scheduledStartTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="调度时间">{{ formatDateTime(viewData.dispatchTime) }}</el-descriptions-item>
        <el-descriptions-item label="调度状态">
          <el-tag :type="getStatusType(viewData.dispatchStatus)">
            {{ getStatusText(viewData.dispatchStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="确认时间">{{ formatDateTime(viewData.surveyorConfirmTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="取消原因" v-if="viewData.dispatchStatus === 5">{{ viewData.cancelReason
          }}</el-descriptions-item>
        <el-descriptions-item label="调度备注" :span="2">{{ viewData.dispatchRemark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Delete,
  Download,
  Edit,
  View
} from '@element-plus/icons-vue'
import hxxp from '@/utils/hxxp'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  reportId: '',
  surveyorWorkNo: '',
  dispatchStatus: null,
})

// 表格数据
const tableData = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  dispatchId: null,
  reportId: '',
  policyId: '',
  dispatcherWorkNo: '',
  dispatchTime: '',
  surveyorWorkNo: '',
  surveyAddress: '',
  scheduledStartTime: '',
  dispatchStatus: 1,
  dispatchRemark: '',
  surveyorConfirmTime: '',
  cancelReason: ''
})

// 查看数据
const viewData = reactive({})

// 表单验证规则
const formRules = {
  dispatchStatus: [
    { required: true, message: '请选择调度状态', trigger: 'change' }
  ],
  cancelReason: [
    { required: true, message: '请输入取消原因', trigger: 'blur' }
  ]
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'warning',  // 待确认
    2: 'info',     // 已确认
    3: 'primary',  // 查勘中
    4: 'success',  // 查勘完成
    5: 'danger'    // 已取消
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待确认',
    2: '已确认',
    3: '查勘中',
    4: '查勘完成',
    5: '已取消'
  }
  return statusMap[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取调度列表
const getDispatchList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await hxxp.get('/aiClaimDispatch/list', { params })
    console.log(response);

    if (response.code === 100200) {
      tableData.value = response.data.list
      pagination.total = response.data.total || 0
      pagination.currentPage = response.data.pageNum || 1
      pagination.pageSize = response.data.pageSize || 5
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取调度列表失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getDispatchList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (typeof searchForm[key] === 'string') {
      searchForm[key] = ''
    } else {
      searchForm[key] = null
    }
  })
  pagination.currentPage = 1
  getDispatchList()
}


// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑调度'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  Object.assign(viewData, row)
  viewDialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除调度记录吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await hxxp.delete(`/aiClaimDispatch/${row.dispatchId}`)

    if (response.code === 100200) {
      ElMessage.success('删除成功')
      getDispatchList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const response = await hxxp.get('/aiClaimDispatch/export', {
      params,
      responseType: 'blob'
    })

    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `调度信息_${new Date().toISOString().slice(0, 10)}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getDispatchList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getDispatchList()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    dispatchId: null,
    reportId: '',
    policyId: '',
    dispatcherWorkNo: '',
    dispatchTime: '',
    surveyorWorkNo: '',
    surveyAddress: '',
    scheduledStartTime: '',
    dispatchStatus: 1,
    dispatchRemark: '',
    surveyorConfirmTime: '',
    cancelReason: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    const response = await hxxp.put(`/aiClaimDispatch/${formData.dispatchId}`, formData)

    if (response.code === 100200) {
      ElMessage.success('更新成功')
      dialogVisible.value = false
      getDispatchList()
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    if (error !== false) { // 表单验证失败时 error 为 false
      console.error('提交失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 组件挂载时获取数据
onMounted(() => {
  getDispatchList()
})
</script>

<style scoped>
.dispatch-list-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 0;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-section {
  margin-bottom: 20px;
}

.table-section .el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dispatch-list-container {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .action-section {
    flex-direction: column;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f8f9fa;
  color: #495057;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #f8f9fa;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 6px;
  font-weight: 500;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #495057;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 6px;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 20px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0 2px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 6px;
}
</style>